<template>
  

  <div class="contract-container">
    <!-- 患者查询区域 -->
     
    <div class="search-section">
      患者姓名:
      <el-input v-model="RecordNames.RecordName" style="width: 200px;" placeholder="请输入" label="查询患者" />
      <el-button style="margin-left: 10px;" type="primary" @click="RecordScign">查询</el-button>
    </div>

    <!-- 患者信息区域 -->
    <el-card class="patient-info-card">
      <div class="patient-info">
        <span style="font-weight: bold;">{{ patientInfo.recordName }}</span>
        <span style="color: gray;">{{ patientInfo.recordSex }} {{ patientInfo.recordAge }}岁</span>
        <span style="color: gray;">出生日期: {{ patientInfo.recordBirth }}</span>
        <span style="color: gray;">身份证号: {{ patientInfo.recordIdcard }}</span>
      </div>
    </el-card>

    <!-- 签约信息区域 -->
    <el-card class="sign-info-card">
      <el-form
        ref="ruleFormRef"
        style="max-width: 100%"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="签约团队">
              <el-select v-model="ruleForm.cSignTeam" placeholder="请选择签约团队" style="width: 300px;">
                <el-option label="沙河社区家庭医生团队" value="沙河社区家庭医生团队"></el-option>
                <!-- 可根据实际需求添加更多选项 -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签约医生">
              <el-select v-model="ruleForm.cSignDoctor" placeholder="请选择主管医生" style="width: 300px;">
                <el-option label="豆豆" value="豆豆"></el-option>
                <!-- 可根据实际需求添加更多选项 -->
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="签约周期">
          <el-date-picker v-model="ruleForm.cSignBegin" type="date" placeholder="yyyy/mm/dd" />
          ~
          <el-date-picker v-model="ruleForm.cSignEnd" type="date"  placeholder="yyyy/mm/dd" />
        </el-form-item>
        <el-form-item label="管理慢病">
          <el-select v-model="ruleForm.cSignManage" placeholder="请选择管理慢病" style="width: 300px;">
                <el-option label="原发性高血压" value="原发性高血压"></el-option>
                <el-option label="2型糖尿病" value="2型糖尿病"></el-option>
                <el-option label="慢阻肺" value="慢阻肺"></el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="管理级别">
          <el-select v-model="ruleForm.cSignLevel" placeholder="请选择管理级别" style="width: 300px;">
            <el-option label="一级" value="一级"></el-option>
            <!-- 可根据实际需求添加更多选项 -->
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 服务包区域 -->
    <el-card class="service-package-card">
      <el-table :data="servicePackages" border style="width: 100%">
        <el-table-column prop="checked" label="选择">
          <template #default="scope">
            <el-checkbox v-model="scope.row.checked"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="服务名称"></el-table-column>
        <el-table-column prop="fee" label="费用"></el-table-column>
        <el-table-column prop="operation" label="操作">
          <template #default="scope">
            <el-button type="text" @click="handleServiceOperation(scope.row)">服务项目</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 绑定设备区域 -->
    <el-card class="device-card">
      <el-table :data="devices" border style="width: 100%">
        <el-table-column prop="name" label="设备名称"></el-table-column>
        <el-table-column prop="sn" label="设备SN号"></el-table-column>
        <el-table-column prop="bindTime" label="绑定时间"></el-table-column>
        <el-table-column prop="status" label="状态"></el-table-column>
        <el-table-column prop="operation" label="操作">
          <template #default="scope">
            <el-button type="text" @click="handleDeviceUnbind(scope.row)">解绑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 签约凭证区域 -->
    <el-card class="voucher-card">
      <el-upload
        class="avatar-uploader"
        action="http://localhost:5203/api/Images/img"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="ruleForm.cSignImage" :src="ruleForm.cSignImage" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <div class="voucher-tip">说明：支持上传jpg、png、pdf文件格式，大小不超过3M。</div>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="button-group">
     <el-form-item>
      <el-button  @click="CSclear"> 取消 </el-button>
      <el-button type="success" @click="resetForm(ruleFormRef)">提交</el-button>
    </el-form-item>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Read, Write } from '@/Http/Axios';

const locationOptions = ['Home', 'Company', 'School']
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.cSignImage = response;
}
// 患者查询输入
const patientQuery = ref('');

// 签约表单数据（与后端双向绑定）
interface RuleForm {
  cSignTeam: string,
  cSignDoctor: string,
  cSignBegin: Date,
  cSignEnd: Date,
  cSignManage: string,
  cSignLevel: string,
  cSignImage: string,
  recordId:number,
}
///清空//重置
const CSclear=()=>({
  cSignTeam: '',
  cSignDoctor: '',
  cSignBegin: '',
  cSignEnd: '',
  cSignManage: '',
  cSignLevel: '',
  cSignImage: '',
  recordId:0,   
})
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  cSignTeam: '沙河社区家庭医生团队',
  cSignDoctor: '豆豆',
  cSignBegin: new Date(),
  cSignEnd: new Date(),
  cSignManage: '',
  cSignLevel: '一级',
  cSignImage: '',
  recordId:0,   
})
// 患者信息接口定义
interface PatientInfo {
  recordName: string;
  recordSex: number | string;
  recordAge: number;
  recordBirth: string;
  recordIdcard: string;
  [key: string]: any; // 允许其他属性
}

// 患者查询输入
const RecordNames = ref<{ RecordName: string }>({ RecordName: '' })

// 患者信息
const patientInfo = ref<PatientInfo>({
  recordName: '张三',
  recordSex: '女',
  recordAge: 29,
  recordBirth: '2001-04-19',
  recordIdcard: '513030********0898'
})

const RecordScign = () => {
  // 确保传递正确的参数格式
  Read.get('http://localhost:5108/api/Manager/ShowRecordCsign', { 
    params: { 
      RecordName: RecordNames.value.RecordName 
    } 
  })
    .then((res) => {
      console.log(res.data.data)
      // 确保响应数据结构正确
      if (res.data.data && res.data.data.length > 0) {
        // 假设返回的数据是患者记录数组，取第一条记录
        const patientData = res.data.data[0];
        ruleForm.recordId = patientData.recordId || 0;
        
        // 更新患者信息显示
        patientInfo.value = {
          recordName: patientData.recordName || '未知',
          recordSex: patientData.recordSex || '未知',
          recordAge: patientData.recordAge || 0,
          recordBirth: patientData.recordBirth || '未知',
          recordIdcard: patientData.recordIdcard || '未知'
        };
        
        console.log('患者ID已设置:', ruleForm.recordId);
        console.log('患者信息已更新:', patientInfo.value);
      } else {
        console.warn('未找到匹配的患者记录');
        ruleForm.recordId = 0;
        
        // 重置患者信息为默认值
        patientInfo.value = {
          recordName: '未找到',
          recordSex: '未知',
          recordAge: 0,
          recordBirth: '未知',
          recordIdcard: '未知'
        };
      }
    })
    .catch((error) => {
      console.error('获取数据失败:', error);
    });
};

const rules = reactive<FormRules<RuleForm>>({
  cSignTeam: [
    { required: true, message: '请选择签约团队', trigger: 'blur' },
  ],
  cSignDoctor: [
    { required: true, message: '请选择签约医生', trigger: 'blur' },
  ],
  cSignBegin: [
    { required: true, message: '请选择签约开始时间', trigger: 'blur' },
  ],
  cSignEnd: [
    { required: true, message: '请选择签约结束时间', trigger: 'blur' },
  ],
  cSignManage: [
    { required: true, message: '请选择管理慢病', trigger: 'blur' },
  ],
  cSignLevel: [
    { required: true, message: '请选择管理级别', trigger: 'blur' },
  ],
})
// 服务包列表（与后端双向绑定）
const servicePackages = reactive([
  { checked: true, name: '高血压常规管理包', fee: 0 },
  { checked: true, name: '高血压增值管理包', fee: 200.00 },
]);
// 设备列表（与后端双向绑定）
const devices = reactive([
  { name: '血压计', sn: 'N10023001', bindTime: '2025-10-23 10:10:12', status: '在绑' },
  { name: '血糖仪', sn: 'N10023002', bindTime: '2025-10-23 10:10:12', status: '在绑' },
]);
// 处理服务操作
const handleServiceOperation = (row: any) => {
  // 可在此处添加服务项目操作逻辑，如弹窗展示服务详情等
  console.log('服务项目操作：', row);
};
// 处理设备解绑
const handleDeviceUnbind = (row: any) => {
  // 可在此处添加设备解绑逻辑，如调用后端接口等
  console.log('设备解绑：', row);
};
// 处理添加签约凭证
const handleAddVoucher = () => {
  // 可在此处添加手动选择文件的逻辑
  console.log('添加签约凭证');
};
// 处理保存操作（调用后端接口，提交所有表单数据）
  // 整合所有数据，调用后端接口
const resetForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      Write.post('http://localhost:5203/api/Managment/AddCSign',ruleForm ).then(res => {
        console.log(res.data);
        if (res.data.code == 1) {
          console.log('提交数据到后端：', res.data);
          ElMessage.success('签约成功');
        }
      }).catch(err => {
        console.log(err);
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
  // 此处可调用axios等发送请求到后端
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('仅支持jpg格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}
const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

<style scoped>
.contract-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
.search-section {
  margin-bottom: 20px;
}
.patient-info-card,
.sign-info-card,
.service-package-card,
.device-card,
.voucher-card {
  margin-bottom: 20px;
}
.patient-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.voucher-upload {
  margin-bottom: 10px;
}
.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>